using System.Collections.Generic;
using System.Data;

namespace DataScripter.Scripting.Processes.Morphs
{
    public class TableMorphAction : ITableMorphAction
    {
        protected List<IFieldMorphAction> MorphActions { get; private set; }
        public string TableNameFilter { get; set; }

        public TableMorphAction(string tableNameFilter)
        {
            MorphActions = new List<IFieldMorphAction>();
            TableNameFilter = tableNameFilter;
        }

        public bool ShouldBeAppliedOnTable(string tableName)
        {
            if (TableNameFilter == "*")
                return true;
            return TableNameFilter == tableName;
        }

        public void Apply(DataSet dataset, string from)
        {
            DataTable morphTarget = dataset.Tables.Add(from + "__Morphed");
            foreach (IFieldMorphAction morphAction in MorphActions)
            {
                morphAction.Apply(dataset.Tables[from], morphTarget);
            }
            foreach (DataRow dataRow in dataset.Tables[from].Rows)
            {
                DataRow newRow = morphTarget.NewRow();
                foreach (IFieldMorphAction morphAction in MorphActions)
                {
                    morphAction.Apply(dataRow, newRow, dataset.Tables[from], morphTarget);
                }
                morphTarget.Rows.Add(newRow);
            }
            dataset.Tables.Remove(from);
            morphTarget.TableName = from;
        }

        public void Add(IFieldMorphAction morphAction)
        {
            MorphActions.Add(morphAction);
        }

    }
}